# -*- coding: utf-8 -*-
import datetime
import math
import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time, urljoin, json, urlencode
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class FujianZfxxgkPolicy(BaseTaxPolicySpider):
    name = 'fujian_fuzhou_zfxxgk_policy'

    province = '福建省'
    city = '福州市'
    # county = ''
    park = ''
    page_size = int(26 * 1.5)

    def __init__(self, get_next=False, **kwargs):
        super().__init__(**kwargs)
        print(get_next)
        self.get_next = get_next

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                # "COOKIES_ENABLED": False,
                "DOWNLOAD_TIMEOUT": 200,
                # "CONCURRENT_REQUESTS": 2,
                "HTTPERROR_ALLOWED_CODES": [302, 400, 404, 407, 500, 200, 202, 502, 429, 521],
                # "DOWNLOAD_DELAY": 5,
                # "DOWNLOADER_MIDDLEWARES": {
                #     "components.middlewares.downloadmiddlewares.public.jsl_middlewares.JslMiddleware": 543,
                #     **downloader_middlewares
                # }
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url in [
            ["莆田市退役军人事务局", "", "https://www.putian.gov.cn/zfxxgk/bmzfxxgk/tyjrswj/zfxxgk/xzgfxwj/"],
            ["莆田市生态环境局", "", "https://sthjj.putian.gov.cn/zfxxgk/xzgfxwj/"],
            ["莆田市文化和旅游局", "", "https://www.putian.gov.cn/zfxxgk/bmzfxxgk/ptwgj/zfxxgk/xzgfxwj/"],
            ["莆田市自然资源局", "", "https://zrzyj.putian.gov.cn/zfxxgk/xzgfxwj/"],
            ["莆田市财政局", "", "https://czj.putian.gov.cn/zfxxgk/xzgfxwj/"],
            ["莆田市交通运输局", "", "https://jtysj.putian.gov.cn/zfxxgk/xzgfxwj/"],
            ["莆田市发展和改革委员会", "", "https://fgw.putian.gov.cn/xxgk/zfxxgk/xzgfxwj/"],
            ["莆田市市场监督局", "", "https://scjgj.putian.gov.cn/zfxxgk/zc/xzgfxwj/"],
            ["莆田市人力资源和社会保障局", "", "https://rsj.putian.gov.cn/zwgk/zfxxgk/zc/xzgfxwj/"],
        ]:
            yield scrapy.Request(url, callback=self._parser_dataproxy_html,
                                 meta={"item": {'source': source, 'county': county}})

    def _parser_dataproxy_html(self, response):
        meta = response.meta
        ul = response.xpath('.')

        classsql = ul.re_first(r"""(chnlid=\d+)""")
        # classcol = ul.re_first(r"""classcol:\s*["']?(.*?)["']?,""")
        channelid = ul.re_first(r"""was4doc\s*:\s*["']?(\d+)["']?,?\s*""")
        data = {
            'sortfield': '-pubdate',
            'channelid': str(channelid),
            'templet': 'docs.jsp',
            'classsql': f'({str(classsql)}*(efftype!=%02,03%))',
            'prepage': str(75),
            'page': str(1),
        }
        url = response.urljoin('/was5/web/search')
        if url[-1] != "?":
            url += "?"
        temp_url = url + urllib.parse.urlencode(data)
        meta.update({
            "data": data,
            "url": url,
        })
        print(data)
        yield self.Request(
            temp_url,
            callback=self.parse_list,
            dont_filter=True,
            meta=meta
        )

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        meta = response.meta
        data = json.loads(response.text.replace('\n', ''))
        url_list = data['docs']
        for elem in url_list:
            if elem['url'] == '链接':
                continue
            item = Item()
            item['source_url'] = elem['chnldocurl']
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem['pubdate'].replace("年", "-").replace("月", "-")[:-1]
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        page = meta.get('page', 1)
        if meta.get("is_next") is False:
            return
        total_page = math.ceil(int(data['count']) / 75)
        print(meta['data'], page, "total_page", total_page)
        meta['is_next'] = False
        for page in list(range(2, total_page + 1)):
            data = meta.get("data")
            data['page'] = str(page)
            url = meta.get('url')
            temp_url = url + urllib.parse.urlencode(data)
            self.logger.info(f"{total_page} 开始爬取 第 {page} 页 data: {data}")
            yield self.Request(
                temp_url,
                meta=meta,
                callback=self.parse_list,
                dont_filter=True
            )

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath(
            "//*[@class='fbrq']/text()").get()
        if item['publish_date']:
            item['publish_date'] = item['publish_date'].split(" ")[0]
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl fujian_fuzhou_zfxxgk_policy -a get_next=0".split())
